package com.chyer.logistics_interest.serviceImpl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chyer.logistics_interest.entity.stock.SHStockEnum;
import com.chyer.logistics_interest.entity.stock.SZStockEnum;
import com.chyer.logistics_interest.entity.stock.StockModel;
import com.chyer.logistics_interest.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;

@Slf4j
@Service
public class StockServiceImpl implements StockService {


    private final String INFO_URL = "http://api.mairui.club/hsrl/ssjy/";

    //private final String token = "F72E65ED-3D5C-45E0-A661-39620214027A";
    private final String token = "B108CCCB-EBAD-41C8-A378-6F179F3BA336";

    private final String stockList = "";



    @Override
    public StockModel getStockInfoByCode(String code) {
//        StringBuilder sb = new StringBuilder("");
//        JSONArray array = JSONArray.parseArray(stockList);
//        log.info("==== array = {}", array);
//        List<JSONObject> stockList = new ArrayList<>();
//        if(array != null && array.size() > 0){
//            for(int i = 0 ; i<array.size(); i++){
//                JSONObject tem = array.getJSONObject(i);
//                stockList.add(tem);
//            }
//        }
//        log.info("==== stockList = {}", stockList);

        String url = INFO_URL + code + "/" + token;
        String result = null;
        try {
            HttpClient httpClient=new DefaultHttpClient();
            HttpGet requestGet=new HttpGet(url);
            //requestPost.addHeader("Content-type","application/json; charset=utf-8");
            requestGet.setHeader("Accept", "application/json");
            requestGet.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            HttpResponse response = httpClient.execute(requestGet);
            if(response.getStatusLine().getStatusCode()==200){
                HttpEntity entity = response.getEntity();
                result= EntityUtils.toString(entity,"utf-8");
            }
        } catch (Exception e) {
            log.info("发送 Get 请求出现异常！" + e);
            e.printStackTrace();
        }
        //log.info("==== result = {}", result);
        StockModel stock = transfterToStock(result);
        stock.setStockCode(code);
        SHStockEnum shStock = SHStockEnum.getByCode(code);
        if(shStock != null){
            stock.setStockName(shStock.getName());
        }else{
            SZStockEnum szStock = SZStockEnum.getByCode(code);
            if(szStock != null){
                stock.setStockName(szStock.getName());
            }
        }
        log.info("======= stock = {}", JSON.toJSON(stock));
        return stock;
    }

    @Override
    public List<StockModel> listStockInfoByCodes(List<String> codes) {
        List<StockModel> stockList = new ArrayList<>();
        if(codes != null && codes.size() > 0){
            for(String code : codes){
                StockModel tem = getStockInfoByCode(code);
                stockList.add(tem);
            }


        }
        return stockList;
    }


    //==== result = {"o":21.48,"fm":0.0,"h":22.5,"hs":4.33,"lb":2.86,"l":21.01,"lt":8671428143.0,"pe":58.9,"pc":9.98,"p":22.49,"sz":8686730339.0,"cje":366230551.0,"ud":2.04,"v":167046,"yc":20.45,"zf":7.29,"zs":0.04,"sjl":1.75,"zdf60":7.2,"zdfnc":-11.84,"t":"2024-09-30 15:29:04"}

    private StockModel transfterToStock(String data){
        StockModel stock = new StockModel();
        if(StringUtils.isNotBlank(data)){
            JSONObject object = JSONObject.parseObject(data);

            stock.setFiveMin(object.getString("fm"));//五分钟涨跌幅（%）
            stock.setHighPrice(object.getString("h")); //最高价（元）
            stock.setLowPrice(object.getString("l")); //最 低 价（元）
            stock.setOpenPrice(object.getString("o")); //开盘价（元）
            stock.setCurrentPrice(object.getString("p")); //当前价格（元）
            stock.setChangeHand(object.getString("hs")); //换手（%）
            stock.setUpdateTime(object.getString("t")); //更新时间yyyy-MM-dd HH:mm:ss
            stock.setDealNum(object.getString("v")); //成交量（手）
            stock.setFlow(object.getString("lt")); //流通市值（元）
            stock.setYesterdayPrice(object.getString("yc")); //昨日收盘价（元）
            stock.setTotalMarketPrice(object.getString("sz")); //总市值（元）
            stock.setRisePrice(object.getString("ud")); //涨跌额（元）
        }

        return stock;
    }




    public static void main(String[] args) {
        try {
            // 读取JSON文件内容
            BufferedReader reader = new BufferedReader(new FileReader("D:\\personSelf\\stock.json"));
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
            reader.close();

            // 解析JSON
            JSONArray jsonArray = JSONArray.parseArray(content.toString());
            Map<Integer, String> map = new TreeMap<>();
            // 遍历JSONArray并获取每个元素
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject element = jsonArray.getJSONObject(i);
                StringBuilder sb = new StringBuilder("");
                //String value = element.getString("key");
                //     A("00000", "上证指数","sh");
                String code = element.getString("dm");//代码
                String name = element.getString("mc");//名称
                String type = element.getString("jys");//交易所

//                 //A("00000", "上证指数","sh");
//                sb.append('"').append(code).append('"')
//                        .append(",").append('"').append(name).append('"')
//                        .append(",").append('"').append(type).append('"')
//                        .append(")");

                sb.append('"').append(name).append('_').append(type).append('"');

                map.put(Integer.valueOf(code), sb.toString());
               // System.out.println(sb.toString());
            }

            for (Map.Entry<Integer, String> entry : map.entrySet()) {
                StringBuilder tem = new StringBuilder("items.put(");
                Integer key = entry.getKey();
                String code = String.format("%06d", key);
                tem.append('"').append(code).append('"').append(",")
                   .append(entry.getValue()).append(");");
                System.out.println(tem.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
